<template>
	<z-paging
		ref="paging"
		style="min-height: 100%; background: rgba(255, 255, 255, 1)"
		v-model="dataList"
		:show-loading-more-when-reload="true"
		:refresher-enabled="false"
		:auto-show-back-to-top="true"
		@query="queryList"
	>
		<!-- z-paging默认铺满全屏，此时页面所有view都应放在z-paging标签内，否则会被盖住 -->
		<!-- 需要固定在页面顶部的view请通过slot="top"插入，包括自定义的导航栏 -->
		<view class="img-panel">
			<view class="img-item" v-for="(item, index) in dataList" :key="index">
				<image style="height: 320rpx" mode="aspectFit" :src="item" @tap="preview(item)" />
			</view>
		</view>
		<q-previewImage ref="previewImage" :urls="dataList" @onLongpress="onLongpress"></q-previewImage>

		<template #bottom>
			<tabbar :current="1"></tabbar>
		</template>
	</z-paging>
</template>

<script setup>
import { ref, defineProps } from 'vue';
import HomeAPI from '@/api/home/api.ts';
import GrowthApi from '@/api/growth/api';
import tabbar from '@/components/tabbar/index.vue';
import { onBackPress } from '@dcloudio/uni-app';
const paging = ref(null);
const dataList = ref([]);
const previewImage = ref(null);

// @query所绑定的方法不要自己调用！！需要刷新列表数据时，只需要调用paging.value.reload()即可
const queryList = (pageNo, pageSize) => {
	// 此处请求仅为演示，请替换为自己项目中的请求
	let params = {
		pageNum: pageNo,
		pageSize: 20
	};
	GrowthApi.getActivityPhotoPage(params)
		.then(({ data }) => {
			paging.value.complete(data.list);
		})
		.catch(() => {
			paging.value.complete(false);
		});
};

const preview = (url) => {
	// #ifdef MP-WEIXIN
	this.$nextTick(() => {
		previewImage.value.open(url); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
	});
	// #endif

	// #ifndef MP-WEIXIN
	previewImage.value.open(url); // 传入当前选中的图片地址
	// #endif
};

function handleSave(imgUrl) {
	uni.saveImageToPhotosAlbum({
		filePath: imgUrl,
		success: function () {
			uni.showToast({
				title: '保存成功',
				icon: 'none'
			});
		},
		fail: function (e) {
			console.log(e);
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			});
		}
	});
}

const onLongpress = (e) => {
	// #ifdef APP-PLUS
	uni.showActionSheet({
		itemList: ['保存到手机'],
		success: function (res) {
			if (res.tapIndex == 0) {
				handleSave(e);
			}
		},
		fail: function (res) {
			console.log(res.errMsg);
		}
	});
	// #endif
};

onBackPress(() => {
	uni.sendNativeEvent('closeMe', { delay: 10 }, (res) => {
		console.log('closeMe----' + JSON.stringify(res));
	});
});
</script>
<style scoped lang="scss">
.img-panel {
	display: flex;
	flex-wrap: wrap;
	.img-item {
		padding: 5rpx 10rpx;
		box-sizing: border-box;
		width: calc(50% - 10rpx);
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(0, 0, 0, 0.01);
		margin: 5rpx 5rpx;
	}
}
</style>
